package com.jiaok.config;

import com.jiaok.config.securityHandler.FailedAccessDeniedHandler;
import com.jiaok.config.securityHandler.FailedAuthenticationEntryPoint;
import com.jiaok.filter.CaptchaFilter;
import com.jiaok.filter.JwtAuthenticationTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Author jiaok
 * @Date 2023/5/4 16:00
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfigureAdapter extends WebSecurityConfigurerAdapter {
    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    private CaptchaFilter captchaFilter;
    @Resource
    private FailedAccessDeniedHandler failedAccessDeniedHandler;
    @Resource
    private FailedAuthenticationEntryPoint failedAuthenticationEntryPoint;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext---前后端分离项目，session没法使用
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        //将jwt过滤器添加到，用户名密码权限验证器之前
        http
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//        配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(failedAuthenticationEntryPoint)//认证失败
                .accessDeniedHandler(failedAccessDeniedHandler);//授权失败

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        //加密操作
        return new BCryptPasswordEncoder();
    }
}
